package com.sh.util;


import com.alibaba.nacos.common.utils.ConcurrentHashSet;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class LoadStatistic {

    /**
     * KEY=gatewayserverId
     * value=userId的集合
     */
    static private Map<Integer, Set<Integer>> _userIdMap = new ConcurrentHashMap<>();

    public LoadStatistic() {
    }


    static public int get() {

        return _userIdMap.values().stream()
                .mapToInt(Set::size)
                .sum();
    }

    static public void addUserId(int gatewayServerId, int userId) {
        if (gatewayServerId <= 0 || userId <= 0) {
            return;
        }
        if (!_userIdMap.containsKey(gatewayServerId)) {
            _userIdMap.put(gatewayServerId,
                    new ConcurrentHashSet<>());
        }
        Set<Integer> userIds = _userIdMap.get(gatewayServerId);
        if (null != userIds) {
            userIds.add(userId);
        }
    }

    /**
     * 减少人数
     *
     * @param userId
     */
    static public void removeUserId(int userId) {
        if (userId <= 0) {
            return;
        }
        _userIdMap.values().forEach(set -> set.remove(userId));
    }

    /**
     * 移除网关服务器 id
     * @param gatewayServerId  网关服务器id
     */
    static public void removeGatewayServerId(int gatewayServerId) {
        if (gatewayServerId > 0) {
            _userIdMap.remove(gatewayServerId);
        }
    }
}
